<template>
  <div class="subject-right">
    <div class="subject-right-header">
      <div class="resourceTop">
        <div class="text">
          <p class="title007">标签信息</p>
          <p>
            <span>共&nbsp;{{ tableDatas.length }}&nbsp;个标签类别</span>
          </p>
        </div>
        <div class="nav-right">
          <el-button size="large" round @click="openDialog('create')" color="#d11431"
            style="color: #fff">创建标签</el-button>
          <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
            <el-form :model="form" :rules="rules" ref="ruleFormRef" status-icon>
              <el-form-item label="请输入标签名" prop="name" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off" />
              </el-form-item>
              <el-form-item label="所属专业" prop="region" :label-width="formLabelWidth">
                <el-select v-model="form.region" filterable placeholder="输入您所添加标签的所属专业" style="width: 240px">
                  <el-option
                    v-for="item in directions"
                    :key="item.directionId"
                    :label="item.directionName"
                    :value="item.directionId"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
    <div class="subject-right-body">
      <div class="table">
        <el-table :data="filteredTableDatas" height="74vh" style="width: 100%" empty-text="当前没有标签" @row-click="acs"
          :row-style="{ height: '80px' }">
          <el-table-column prop="labelId" label="标签编号" align="center" />
          <el-table-column prop="labelName" label="标签名称" align="center" sortable />
          <el-table-column prop="directionName" label="所属专业" align="center" sortable />
          <el-table-column prop="id" label="管理" align="center">
            <template #default="scope">
              <el-tooltip content="修改标签名称" placement="left">
                <el-button type="info" size="mini" round @click="openDialog('edit', scope.row)" :icon="Edit" />
              </el-tooltip>
              <el-tooltip content="删除当前标签" placement="right">
                <el-button type="danger" size="mini" round @click="deleteTag(scope.row.labelId)" :icon="Delete" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { ElMessageBox,ElMessage } from 'element-plus';
import {
  Delete,
  Edit,
  Search,
} from '@element-plus/icons-vue';
import {
  addLabel,
  deleteClass,
  updateClass,
  deleteLabel,
  updateLabel,
  selectAllDirection,
} from '@/api/teacher/AddClass';
import { directionList } from '@/api/courseManager';
import type { ComponentSize } from 'element-plus'
const currentPage1 = ref(5)
const currentPage2 = ref(5)
const currentPage3 = ref(5)
const currentPage4 = ref(4)
const pageSize2 = ref(100)
const pageSize3 = ref(100)
const pageSize4 = ref(100)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  //console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  //console.log(`current page: ${val}`)
}
const classNum = ref(0);
// 表单对话框显示
const dialogFormVisible = ref(false);
// 表单label宽度
const formLabelWidth = '140px';
// 班级列表模型
const tableDatas = ref([]);
// 表单数据
const directions = ref([]);
const form = reactive({
  id: null,
  name: '',
  region: ''
});
// 定义表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入标签名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所属专业', trigger: 'change' }
  ]
};

// 查询所有标签名称
const selectAll = async () => {
  let res = await selectAllDirection();
  tableDatas.value = res.data;
}
selectAll();

// 查询所有专业名称
const selectDirection = async () => {
  let res = await directionList();
  directions.value = res.data;

}
selectDirection();

// 创建标签
const addClass = async (name, region) => {
  // 创建专业对象，如果后端是俩个值的传入不需要创建对象如果是对象则将俩值传入对象中
  const newLabel = { labelName: name, majorId: region };
  let aa = await addLabel(newLabel);
  try {
    if (aa.data) {
      ElMessage({
        type: "success",
        message: `添加成功`,
      });
      selectAll();
      dialogFormVisible.value = false;
      // 清空表单数据
      form.name = '';
      form.region = '';
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: `添加失败`,
    });
  }
}


// 删除标签
const deleteTag = async (id) => {
    await ElMessageBox.confirm(
      '此标签下可能会有相对应的题目正在使用, 是否继续?',
      '提示',
      {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    let aa = await deleteLabel(id);
    if (aa.data) {
      ElMessage.success('删除成功');
      selectAll();
    } else {
      ElMessage.error('删除失败');
    }
};

// 修改班级名称
const updateClassFunc = async (id, name, region) => {
  
    const updatedLabel = {labelId:id,labelName: name,majorId: region };
  let aa=  await updateLabel(updatedLabel);
  try {
    if (aa.data) {
      ElMessage({
        type: "success",
        message: `修改成功`,
      });
      selectAll();
      dialogFormVisible.value = false;
      // 清空表单数据
      form.name = '';
      form.region = '';
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: `修改失败`,
    });
  }
}
 

// 搜索班级
const searchText = ref('');
const filteredTableDatas = computed(() => {
  return tableDatas.value.filter(data =>
    data.labelName.toLowerCase().includes(searchText.value.toLowerCase())
  );
});

// 打开对话框
const openDialog = (type, row) => {
  if (type === 'create') {
    dialogTitle.value = '创建标签';
    dialogSubmitText.value = '提交';
    form.id = null;
    form.name = '';
    form.region = '';
  } else if (type === 'edit') {
    dialogTitle.value = '编辑标签';
    dialogSubmitText.value = '保存';
    form.id = row.labelId;
    form.name = row.labelName;
    form.region = row.directionName;
  }
  dialogFormVisible.value = true;
};

// 提交表单
const submitForm = () => {
  if (dialogTitle.value === '创建标签') {
    if (form.name === '' || form.region === '') {
      ElMessage({
        type: "error",
        message: `请输入标签名或所属专业`,
      });
      return;
    }else{
      addClass(form.name, form.region);
    }
    
  } else if (dialogTitle.value === '编辑标签') {
    updateClassFunc(form.id, form.name, form.region);
  }
  dialogFormVisible.value = false;
};

const acs = (row) => {
  //console.log(row); // 处理行点击事件
};

const dialogTitle = ref('');
const dialogSubmitText = ref('');
</script>

<style scoped lang="scss">
@import url(@/assets/font/iconfont.css);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

a {
  text-decoration: none;
}

ul,
ol {
  list-style: none;
}

.resourceTop {
  width: 100%;
  height: 100px;
  background-color: white;
  border: 1px solid #f0f0f0;
  padding: 16px 60px;
}

.resourceTop .logo {
  width: 60px;
  height: 60px;
  background-color: #ff6b0f;
  border-radius: 50%;
  display: inline-block;
  justify-content: center;
  align-items: center;
}

.resourceTop .logo img {
  width: 60px;
  height: 60px;
  padding: 18px;
}

.resourceTop .text {
  width: 120px;
  height: 100%;
  margin-left: 20px;
  display: inline-block;
}

.resourceTop .text .title007 {
  font-size: 22px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 10px;
}

.resourceTop .text p span {
  color: rgba(0, 0, 0, 0.45);
}

.resourceTop .text p a {
  color: #f4523b;
}

.search {
  display: flex;
  float: right;
  border-radius: 2px;
  background-color: #fafafa;
  border: 1px solid #f0f0f0;
}

.sousuo {
  width: 40px;
  height: 40px;
  padding: 11px;
  background-color: #fff;
}

.resourceTop .search input {
  width: 320px;
  height: 40px;
  border: none;
  background-color: #fff;
}

.search input:focus {
  outline: none;
}

.search:hover {
  border: 1px solid #FF6B0F;
}

.nav-right {
  float: right;
  width: 500px;
  height: 100%;
  padding: 14px 0;
}

.subject-right-header {
  width: 100%;
}

.subject-right-body {
  background-color: #eeeeee;
  height: 78.5vh;
  width: 99.9%;
  padding: 24px 60px;
}

.table {
  height: 100px;
  width: 100%;
}

::v-deep .el-table tr:hover {
  cursor: pointer;
}
</style>
